package web;

import base.MemberOfWeChatWork;
import util.MemberUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.qameta.allure.Description;
import org.junit.Assert;
import org.junit.jupiter.api.*;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 作业
 * 1.ceshiren搜索一个帖子并点进去进行查看
 * 2.企业微信实现自动登录
 * 3.在通讯录添加成员
 */
public class HomeWork0414 {
    static WebDriver webDriver;
    static Actions actions;

    /**
     * 企业微信登录URL
     */
    static String WECHART_LOGIN_URL = "https://work.weixin.qq.com/wework_admin/frame";

    /**
     * 企业微信登录扫码成功的xpath
     */
    static String XPATH_LOGINOK = "//div[@class='status_txt']/h4[text()='扫描成功']";

    /**
     * Cookies文件名
     */
    static String COKKIES_FILENAME = "cookies.yaml";

    /**
     * YAML文件父目录
     */
    static String PARENT_DIR_OF_COOKIESFILE;

    /**
     * YAML文件句柄
     */
    static File HANDLE_OF_COOKIES_FILE;

    /**
     * 初始化工作
     * 1、初始化webDriver
     * 2、设置隐式等待
     * 3、初始化Actions
     */
    @BeforeAll
    static void tearUp() {
        webDriver = new ChromeDriver();
        webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        actions = new Actions(webDriver);

        //创建YAML文件的父目录(不管有无)
        PARENT_DIR_OF_COOKIESFILE = new Object() {
            public String getPath() {
                return new StringBuilder(this.getClass().getResource("/").getPath()).append("data").toString();
            }
        }.getPath();
        File dir = new File(PARENT_DIR_OF_COOKIESFILE);
        dir.mkdir();

        HANDLE_OF_COOKIES_FILE = new File(PARENT_DIR_OF_COOKIESFILE, COKKIES_FILENAME);
    }

    @Test
    @Disabled
    void _debug() {

    }

    @AfterAll
    static void tearDown() {
        webDriver.quit();
        //清理测试文件
        //HANDLE_OF_COOKIES_FILE.deleteOnExit();
    }

    @Test
    @DisplayName("搜索并查看帖子")
    @Description("作业1.ceshiren搜索一个帖子并点进去进行查看")
    public void searchAndClick() {
        webDriver.get("https://ceshiren.com/");
        webDriver.findElement(By.id("search-button")).click();
        webDriver.findElement(By.id("search-term")).sendKeys("名企定向");

        List<WebElement> eList = webDriver.findElements(By.xpath("//div[@class='search-result-topic']//a[@class='widget-link search-link']"));
        if (eList.size() > 0) {
            try {
                eList.get(0).click();
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("没有找到结果，需要尝试其他关键字");
        }
    }

    @Test
    @DisplayName("自动登录企业微信")
    @Description("作业2.企业微信实现自动登录")
    //TODO:Cookie文件失效等异常可单独判断，便于快速定位问题
    public void autoLoginWeChatWork() {
        //打开网页->读取YAML文件并设置Cookies->完成登录
        try {
            webDriver.get(WECHART_LOGIN_URL);

            ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
            TypeReference<List<HashMap<String, Object>>> typeReference = new TypeReference<List<HashMap<String, Object>>>() {
            };

            if (!HANDLE_OF_COOKIES_FILE.exists()) {
                Assert.fail("Cookies文件不存在，请先单独运行Case：loginAndSaveCookies");
            }

            List<HashMap<String, Object>> cookies = objectMapper.readValue(HANDLE_OF_COOKIES_FILE, typeReference);
            cookies.forEach(cookie -> {
                webDriver.manage().addCookie(new Cookie(cookie.get("name").toString(), cookie.get("value").toString()));
            });

            webDriver.navigate().refresh();
            webDriver.findElement(By.id("menu_contacts")).click();
            Thread.sleep(2000);
        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail("发生异常，请检查具体报错");
        }
    }

    @Test
    @DisplayName("手动扫码登录并自动保存Cookies")
    @Description("为了保存登录Cookies的用例，保存Cookies后方便后边自动登录使用，需单独执行该Case")
    @Disabled
    public void loginAndSaveCookies() {
        try {
            //打开企业微信登录页面，手动扫码登录，并判断出现扫描成功字样
            webDriver.get(WECHART_LOGIN_URL);
            Thread.sleep(10000);

            //扫码并确认登录，读取Cookies并存入文件
            Set<Cookie> cookies = webDriver.manage().getCookies();
            ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());

            if (!HANDLE_OF_COOKIES_FILE.exists()) {
                HANDLE_OF_COOKIES_FILE.createNewFile();
            }
            objectMapper.writeValue(HANDLE_OF_COOKIES_FILE, cookies);

            //debug，打印Cookies内容
            //System.out.println("cookies长度为：" + cookies.size());
            //cookies.forEach(cookie -> System.out.println(cookie.getName() + ":" + cookie.getValue()));

        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail("发生异常，请检查具体报错");
        }
    }

    @Test
    @DisplayName("通讯录添加成员")
    @Description("作业3.在通讯录添加成员，时间有限，暂时只写死必填参数，后面优化为数据驱动")
    public void addMemIntoAddressBook() {
        try {
            webDriver.get(WECHART_LOGIN_URL);

            ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
            TypeReference<List<HashMap<String, Object>>> typeReference = new TypeReference<List<HashMap<String, Object>>>() {
            };

            if (!HANDLE_OF_COOKIES_FILE.exists()) {
                Assert.fail("Cookies文件不存在，请先单独运行Case：loginAndSaveCookies");
            }

            List<HashMap<String, Object>> cookies = objectMapper.readValue(HANDLE_OF_COOKIES_FILE, typeReference);
            cookies.forEach(cookie -> {
                webDriver.manage().addCookie(new Cookie(cookie.get("name").toString(), cookie.get("value").toString()));
            });

            webDriver.navigate().refresh();

            //查询并点击进入对应部门下
            webDriver.findElement(By.id("menu_contacts")).click();
            webDriver.findElement(By.id("memberSearchInput")).sendKeys("霍格沃茨");
            webDriver.findElements(By.id("search_party_list")).get(0).click();

            //添加成员
            Thread.sleep(2000);
            webDriver.findElements(By.cssSelector(".js_add_member")).get(1).click();
//            webDriver.findElement(By.xpath("//div[@class='ww_operationBar']/a[@class='qui_btn ww_btn js_add_member']")).click();//可能会失焦

            //构造一个成员并添加进去
            MemberOfWeChatWork member = MemberUtils.creatMember();
            webDriver.findElement(By.name("username")).sendKeys(member.getName());
            webDriver.findElement(By.name("acctid")).sendKeys(member.getAccount());
            webDriver.findElement(By.name("mobile")).sendKeys(member.getMobile());

            //手机号过于真实，取消勾选不发送邀请-_-|||
            if (webDriver.findElement(By.xpath("//input[@name='sendInvite']")).isSelected()) {
                webDriver.findElement(By.xpath("//input[@name='sendInvite']")).click();
            }
            Thread.sleep(7000);

//            webDriver.findElements(By.xpath("//a[@class='qui_btn ww_btn js_btn_save']")).get(1).click();
            webDriver.findElements(By.linkText("保存")).get(1).click();

            Thread.sleep(3000);

            //通过搜索判断已添加成功，先清除现有查询
            webDriver.findElement(By.id("menu_contacts")).click();
            webDriver.findElement(By.id("clearMemberSearchInput")).click();
            webDriver.findElement(By.id("memberSearchInput")).sendKeys(member.getAccount());
            webDriver.findElement(By.xpath("//*[@id='search_member_list']//span[contains(text(),'" + member.getAccount() + "')]"));
            Thread.sleep(5000);

        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail("发生异常，请检查具体报错");
        }
    }

}
